package com.isoft.systemprovidor.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@Slf4j
@RestController
@RequestMapping("systemprovidor/file")
public class FileController {
    @Value("${myfile.download.path}")
    private String downPath ;
    @RequestMapping("/download")
    public void download(String filename , HttpServletRequest request , HttpServletResponse response) throws Exception {
        // 读取要下载的文件源 , File.separator 是路径间隔符
        ClassPathResource pathResource = new ClassPathResource(downPath +
                File.separator + filename) ;
        if(! pathResource.exists()) {
            throw new Exception("下载的文件丢失") ;
        }
        // 设置响应消息头信息
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;filename="+
                URLEncoder.encode(filename, "UTF-8"));
        // 获取输出流 ： 写到网络，然后发送到客户端
        OutputStream os = response.getOutputStream() ;
        // 实例化输入流
        FileInputStream fis = new FileInputStream(pathResource.getFile()) ;
        // IO 流操作的边读编写
        byte[] buffer = new byte[1024] ;
        int len = 0 ;
        while(-1 != (len = fis.read(buffer))) {
            os.write(buffer , 0 , len);
        }
        fis.close();
        log.error("下载结束");
    }
}
